package com.company.threads.chapter;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author xiaohutu
 * @Description: 多线程时间测试
 * @date 2021/1/18 9:50
 */
public class ConcurrencyTest {
    private static final long count = 10000l;

    public static void main(String[] args) {
        concurrentcy();
        serial();
//        ExecutorService service = Executors.newFixedThreadPool(10);
//        service.


    }

    //线程安全的 乐观锁

    private AtomicLong count1 = new AtomicLong(0);

    public void inc() {
        boolean updated = false;
        while (!updated) {
            long prevCount = this.count1.get();
            updated = this.count1.compareAndSet(prevCount, prevCount + 1);
        }
    }

    private static void serial() {
        long start = System.currentTimeMillis();
        int a = 0;
        for (long i = 0; i < count; i++) {
            a += 5;
        }
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("serires time :" + time + "ms,b=" + b + ",a=" + a);
    }

    private static void concurrentcy() {
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a += 5;
                }
                System.out.println(a);
            }
        });
        thread.start();
        int b = 0;
        for (long i = 0; i < count; i++) {
            b--;

        }
        long time = System.currentTimeMillis() - start;
        System.out.println("currency time:" + time + "ms,b=" + b);
    }

}
